package com.mrx.xfriendship.model;

import lombok.Data;
import lombok.experimental.Accessors;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : 肖康宁
 * @since : 2022-12-08 14:33
 **/
@Data
@Accessors(chain = true)
public class SecurityUser implements UserDetails {

    private Integer id;

    private String name;

    private String pass;

    private List<String> role;

    public UsernamePasswordAuthenticationToken toAuthentication() {
        // 将 UserDetails 转换为 Authentication, 第一个参数是 UserDetails, 第二个参数是 rawPassword, 第三个参数是 Authorities
        return new UsernamePasswordAuthenticationToken(this, pass, getAuthorities());
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return role.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
    }

    @Override
    public String getPassword() {
        return pass;
    }

    @Override
    public String getUsername() {
        return name;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

}
